package com.psp.park.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.northend.util.AppTextUtil;
import com.northend.util.MD5Util;
import com.northend.util.RandomUtil;
import com.northend.util.StringUtil;
import com.northend.util.VCodeSender;
import com.psp.park.cache.dao.UserCacheDao;
import com.psp.park.cache.dao.VisitorCacheDao;
import com.psp.park.constants.StringConstants;
import com.psp.park.controller.res.bean.RVisiterBean;
import com.psp.park.model.Code;
import com.psp.park.model.ParkAdminVisitorBean;
import com.psp.park.model.ParkUserBean;
import com.psp.park.model.VisitorBean;
import com.psp.park.persist.dao.UserDao;
import com.psp.park.persist.dao.VisitorDao;
import com.psp.park.service.VisitorService;
import com.psp.park.service.exception.ServiceException;

@Service
public class VisitorServiceImpl implements VisitorService {
	Logger logger = Logger.getLogger(VisitorServiceImpl.class);

	@Autowired
	VisitorDao visitorImpl;

	@Autowired
	VisitorCacheDao visitorCacheImpl;

	@Autowired
	UserDao userImpl;

	@Autowired
	UserCacheDao userCacheImpl;

	VCodeSender phoneCode = VCodeSender.getInstance("N1330628", "t7NYh90uB");

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean reg(String userId, String userName, String account, String phoneCode, String imgKey,
			String imgCode) {
		Code code = visitorCacheImpl.getPhoneCode(1, account);
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}
		logger.info("phone is:" + account + ", vcode is:" + phoneCode + ", code = " + code);
		if (!phoneCode.equals(code.getCode())) {
			throw new ServiceException("vcode_is_error");
		}
		VisitorBean user = null;
		boolean isPhone = false;
		if (StringUtil.isMobileNO(account)) {
			isPhone = true;
			user = visitorImpl.selectOneByPhone(account);
		} else if (StringUtil.isEmail(account)) {
			user = visitorImpl.selectOneByEmail(account);
		}
		if (user != null) {
			throw new ServiceException("object_is_exist", new Object[] { "用户" });
		}
		VisitorBean newuser = new VisitorBean();
		String visitorId = AppTextUtil.getPrimaryKey();
		newuser.setUid(visitorId);
		newuser.setNickName(userName);
		newuser.setHeadIcon("http://os4z3g2v6.bkt.clouddn.com/Fm4aPTrJFVacoz0E0xhdIGMWcwwD");// 默认头像
		newuser.setGender(1);// 默认男
		if (isPhone) {
			newuser.setPhone(account);
		} else {
			newuser.setEmail(account);
		}
		newuser.setPassword(isPhone ? MD5Util.sha256Hex(account.substring(5)) : "123456");
		newuser.setState(Integer.valueOf(1));
		boolean flag = visitorImpl.insert(newuser) > 0;
		logger.info("new User is:" + newuser);
		if (!flag) {
			throw new ServiceException("fail");
		}
		ParkAdminVisitorBean pav = new ParkAdminVisitorBean();
		pav.setRid(AppTextUtil.getPrimaryKey());
		pav.setAid(userId);
		pav.setUid(visitorId);
		flag = visitorImpl.insertAdminVisitor(pav) > 0;
		if (!flag) {
			throw new ServiceException("fail");
		}
		return flag;
	}

	@Override
	public PageResult<RVisiterBean> getList(int page, int pageSize, String uid) {
		if (StringUtil.isEmpty(uid)) {
			throw new ServiceException("token_fail");
		}
		ParkUserBean admin = userImpl.selectOne(uid);
		if (admin == null) {
			throw new ServiceException("object_is_not_exist", "业务员");
		}

		PageResult<RVisiterBean> result = new PageResult<RVisiterBean>();
		List<RVisiterBean> data = new ArrayList<>();
		int count = visitorImpl.selectCount(uid);
		List<VisitorBean> reslist = visitorImpl.selectList(page, pageSize, uid);

		if (reslist != null && reslist.size() > 0) {
			for (VisitorBean v : reslist) {
				RVisiterBean rvisitor = new RVisiterBean();
				rvisitor.setAccount(v.getPhone());
				rvisitor.setUid(v.getUid());
				rvisitor.setCreateTime(v.getCreateTime() != null ? v.getCreateTime().getTime() : 0);
				rvisitor.setAdmin(admin.getNickName());
				rvisitor.setName(v.getNickName());
				rvisitor.setPark(admin.getPark());
				data.add(rvisitor);
			}
		}
		result.setData(data);
		result.setCount(count);
		return result;
	}

	@Override
	public boolean sendVCode(String phone) {
		long now = System.currentTimeMillis() / 1000;
		VisitorBean user = visitorImpl.selectOneByPhone(phone);
		if (user != null) {
			throw new ServiceException("object_is_exist", new Object[] { "手机号" });
		}
		Code code = visitorCacheImpl.getPhoneCode(1, phone);// 注册用户
		logger.info("vcode is : " + code);
		if (code != null) {
			long passTime = now - code.getTime();
			logger.info("passTime is : " + passTime);
			if (passTime < 60) {
				throw new ServiceException("vcode_in_limit");
			}
		}

		String vcode = RandomUtil.getRandomNum(4);
		logger.info("the phone vcode is : " + vcode);
		Code cacheCode = new Code();
		cacheCode.setCode(vcode);
		cacheCode.setTime(System.currentTimeMillis() / 1000);
		visitorCacheImpl.setPhoneCode(1, phone, cacheCode);
		String msg = StringConstants.getInstance().getString("msg_vcode_send", new Object[] { vcode, 5 });
		phoneCode.send(phone, msg, null);
		return true;
	}

	@Override
	public void checkImgCode(String imgKey, String imgCode) {
		Code code = userCacheImpl.getImgCode(imgKey);
		logger.info("the code is : " + code);
		if (code == null) {
			throw new ServiceException("imgcode_is_expire", "一分钟内有效。");
		}
		imgCode = imgCode.toUpperCase();
		logger.info("set imgcode is : " + imgCode);
		if ((StringUtil.isEmpty(imgCode)) || (!imgCode.equals(code.getCode()))) {
			throw new ServiceException("imgcode_is_error");
		}
	}

}
